#!/bin/bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 10:20:30
# @LastEditTime: 2025-03-14 10:20:35
# @Description: 云监控定时任务脚本
###

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# 日志文件
LOG_FILE="/var/log/cloud_monitor.log"

# 确保日志目录存在
mkdir -p "$(dirname "$LOG_FILE")"

# 添加时间戳到日志
echo "$(date '+%Y-%m-%d %H:%M:%S') - 开始执行云监控任务..." >> "$LOG_FILE"

# 运行各云平台监控
for platform in aliyun huaweicloud aws; do
    if [ -f "$platform/config.ini" ]; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') - 执行 $platform 监控..." >> "$LOG_FILE"
        
        # 检查虚拟环境
        if [ ! -d "$platform/venv" ]; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - 创建 $platform 虚拟环境..." >> "$LOG_FILE"
            cd "$platform"
            python3 -m venv venv
            source venv/bin/activate
            pip install -r requirements.txt >> "$LOG_FILE" 2>&1
            deactivate
            cd ..
        fi
        
        # 运行监控程序
        cd "$platform"
        source venv/bin/activate
        python main.py >> "$LOG_FILE" 2>&1
        deactivate
        cd ..
        
        echo "$(date '+%Y-%m-%d %H:%M:%S') - $platform 监控执行完成" >> "$LOG_FILE"
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') - 跳过 $platform 监控，配置文件不存在" >> "$LOG_FILE"
    fi
done

# 清理旧日志（保留30天）
find /var/log -name "cloud_monitor.log*" -type f -mtime +30 -delete
